package org.jeecg.modules.exTenderAnnQuaInqueryAnn.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.exChargeSetting.entity.ExChargeSetting;
import org.jeecg.modules.exProject.entity.ExProject;
import org.jeecg.modules.exProject.entity.ExSection;
import org.jeecg.modules.exProject.mapper.ExSectionMapper;
import org.jeecg.modules.exProject.service.IExSectionService;
import org.jeecg.modules.exProject.vo.ExProjectParam;
import org.jeecg.modules.gcProject.vo.StatusEnum;
import org.jeecg.modules.website.entity.WebTradeNotice;
import org.jeecg.modules.website.mapper.WebTradeNoticeMapper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.entity.ExGcNoticesection;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.entity.ExTenderAnnQuaInqueryAnn;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.vo.ExTenderAnnQuaInqueryAnnPage;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.service.IExTenderAnnQuaInqueryAnnService;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.service.IExGcNoticesectionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ex_tender_ann_qua_inquery_ann
 * @Author: jeecg-boot
 * @Date: 2024-09-04
 * @Version: V1.0
 */
@Api(tags = "ex_tender_ann_qua_inquery_ann")
@RestController
@RequestMapping("/exTenderAnnQuaInqueryAnn/exTenderAnnQuaInqueryAnn")
@Slf4j
public class ExTenderAnnQuaInqueryAnnController {
    @Autowired
    private IExTenderAnnQuaInqueryAnnService exTenderAnnQuaInqueryAnnService;
    @Autowired
    private IExGcNoticesectionService exGcNoticesectionService;
    @Autowired
    private ExSectionMapper exSectionMapper;
    @Autowired
    private WebTradeNoticeMapper webTradeNoticeMapper;

    /**
     * 分页列表查询
     *
     * @param exTenderAnnQuaInqueryAnn
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "ex_tender_ann_qua_inquery_ann-分页列表查询")
    @ApiOperation(value = "招标公告-分页列表查询", notes = "ex_tender_ann_qua_inquery_ann-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExTenderAnnQuaInqueryAnn>> queryPageList(ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn,
                                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                 HttpServletRequest req) {
        QueryWrapper<ExTenderAnnQuaInqueryAnn> queryWrapper = QueryGenerator.initQueryWrapper(exTenderAnnQuaInqueryAnn, req.getParameterMap());
        Page<ExTenderAnnQuaInqueryAnn> page = new Page<ExTenderAnnQuaInqueryAnn>(pageNo, pageSize);
        IPage<ExTenderAnnQuaInqueryAnn> pageList = exTenderAnnQuaInqueryAnnService.page(page, queryWrapper);
        if (CollectionUtils.isNotEmpty(pageList.getRecords())) {
            List<String> noticesectionIdList = pageList.getRecords().stream().map(ExTenderAnnQuaInqueryAnn::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(noticesectionIdList)) {
                List<ExGcNoticesection> exGcNoticesectionList = exGcNoticesectionService.selectByMainIdList(noticesectionIdList);
                List<String> sectionIdList = exGcNoticesectionList.stream().map(ExGcNoticesection::getBidSectionId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(sectionIdList)) {
                    List<ExSection> sectionList = exSectionMapper.selectBatchIds(sectionIdList);
                    Map<String,String> sectionNameMap= sectionList.stream().collect(Collectors.toMap(ExSection::getId,ExSection::getBidSectionName));
                    for (ExTenderAnnQuaInqueryAnn record : pageList.getRecords()) {
                        List<String> tenderSectionIdList = exGcNoticesectionList.stream().filter(e->Objects.equals(record.getId(),e.getNoticeid())).map(ExGcNoticesection::getBidSectionId).collect(Collectors.toList());
                                List<String> tenderSectionNameList=tenderSectionIdList.stream().map(e->{
                                    return sectionNameMap.get(e);
                                }).collect(Collectors.toList());
                        record.setBidSectionCodes(StringUtils.join(tenderSectionNameList,","));
                    }
                }
            }

        }
        return Result.OK(pageList);
    }

    @GetMapping(value = "/queryByProjectIdList")
    public Result<List<ExTenderAnnQuaInqueryAnn>> queryByProjectIdList(ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn,
                                                                       HttpServletRequest req) {
        LambdaQueryWrapper<ExTenderAnnQuaInqueryAnn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExTenderAnnQuaInqueryAnn::getProjectId, exTenderAnnQuaInqueryAnn.getProjectId());
        List<ExTenderAnnQuaInqueryAnn> list = exTenderAnnQuaInqueryAnnService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param exTenderAnnQuaInqueryAnnPage
     * @return
     */
    @AutoLog(value = "招标公告-添加")
    @ApiOperation(value = "招标公告-添加", notes = "招标公告-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExTenderAnnQuaInqueryAnnPage exTenderAnnQuaInqueryAnnPage) {
        exTenderAnnQuaInqueryAnnPage.getExGcNoticesectionList().forEach(e -> {
            ExGcNoticesection exGcNoticesection = exGcNoticesectionService.selectBySectionId(e.getBidSectionId());
            if (exGcNoticesection != null) {
                throw new JeecgBootException("该标段已有公告，不能重复添加");
            }
        });
        ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn = new ExTenderAnnQuaInqueryAnn();
        BeanUtils.copyProperties(exTenderAnnQuaInqueryAnnPage, exTenderAnnQuaInqueryAnn);
        exTenderAnnQuaInqueryAnnService.saveMain(exTenderAnnQuaInqueryAnn, exTenderAnnQuaInqueryAnnPage.getExGcNoticesectionList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param exTenderAnnQuaInqueryAnnPage
     * @return
     */
    @AutoLog(value = "招标公告-编辑")
    @ApiOperation(value = "招标公告-编辑", notes = "招标公告-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExTenderAnnQuaInqueryAnnPage exTenderAnnQuaInqueryAnnPage) {
        ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn = new ExTenderAnnQuaInqueryAnn();
        BeanUtils.copyProperties(exTenderAnnQuaInqueryAnnPage, exTenderAnnQuaInqueryAnn);
        ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnnEntity = exTenderAnnQuaInqueryAnnService.getById(exTenderAnnQuaInqueryAnn.getId());
        if (exTenderAnnQuaInqueryAnnEntity == null) {
            return Result.error("未找到对应数据");
        }
        exTenderAnnQuaInqueryAnnService.updateMain(exTenderAnnQuaInqueryAnn, exTenderAnnQuaInqueryAnnPage.getExGcNoticesectionList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招标公告-通过id删除")
    @ApiOperation(value = "招标公告-通过id删除", notes = "ex_tender_ann_qua_inquery_ann-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        exTenderAnnQuaInqueryAnnService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "招标公告-批量删除")
    @ApiOperation(value = "招标公告-批量删除", notes = "ex_tender_ann_qua_inquery_ann-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.exTenderAnnQuaInqueryAnnService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "ex_tender_ann_qua_inquery_ann-通过id查询")
    @ApiOperation(value = "招标公告-通过id查询", notes = "ex_tender_ann_qua_inquery_ann-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExTenderAnnQuaInqueryAnn> queryById(@RequestParam(name = "id", required = true) String id) {
        ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn = exTenderAnnQuaInqueryAnnService.getById(id);
        if (exTenderAnnQuaInqueryAnn == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(exTenderAnnQuaInqueryAnn);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "关联标段通过主表ID查询")
    @ApiOperation(value = "关联标段主表ID查询", notes = "关联标段-通主表ID查询")
    @GetMapping(value = "/queryExGcNoticesectionByMainId")
    public Result<List<ExGcNoticesection>> queryExGcNoticesectionListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ExGcNoticesection> exGcNoticesectionList = exGcNoticesectionService.selectByMainId(id);
        return Result.OK(exGcNoticesectionList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param exTenderAnnQuaInqueryAnn
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ExTenderAnnQuaInqueryAnn> queryWrapper = QueryGenerator.initQueryWrapper(exTenderAnnQuaInqueryAnn, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<ExTenderAnnQuaInqueryAnn> exTenderAnnQuaInqueryAnnList = exTenderAnnQuaInqueryAnnService.list(queryWrapper);

        // Step.3 组装pageList
        List<ExTenderAnnQuaInqueryAnnPage> pageList = new ArrayList<ExTenderAnnQuaInqueryAnnPage>();
        for (ExTenderAnnQuaInqueryAnn main : exTenderAnnQuaInqueryAnnList) {
            ExTenderAnnQuaInqueryAnnPage vo = new ExTenderAnnQuaInqueryAnnPage();
            BeanUtils.copyProperties(main, vo);
            List<ExGcNoticesection> exGcNoticesectionList = exGcNoticesectionService.selectByMainId(main.getId());
            vo.setExGcNoticesectionList(exGcNoticesectionList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "ex_tender_ann_qua_inquery_ann列表");
        mv.addObject(NormalExcelConstants.CLASS, ExTenderAnnQuaInqueryAnnPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ex_tender_ann_qua_inquery_ann数据", "导出人:" + sysUser.getRealname(), "ex_tender_ann_qua_inquery_ann"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ExTenderAnnQuaInqueryAnnPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ExTenderAnnQuaInqueryAnnPage.class, params);
                for (ExTenderAnnQuaInqueryAnnPage page : list) {
                    ExTenderAnnQuaInqueryAnn po = new ExTenderAnnQuaInqueryAnn();
                    BeanUtils.copyProperties(page, po);
                    exTenderAnnQuaInqueryAnnService.saveMain(po, page.getExGcNoticesectionList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    @AutoLog(value = "提交送审")
    @ApiOperation(value = "提交送审", notes = "提交送审")
    @PostMapping(value = "/submitAudit")
    public Result<String> submitAudit(@RequestParam(name = "id", required = true) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExTenderAnnQuaInqueryAnn exTenderAnnQuaInqueryAnn = exTenderAnnQuaInqueryAnnService.getById(id);
        if (exTenderAnnQuaInqueryAnn == null) {
            return Result.error("未找到对应数据");
        }
        exTenderAnnQuaInqueryAnn.setStatus(StatusEnum.SUBMIT.getCode());
        exTenderAnnQuaInqueryAnn.setUpdateTime(new Date());
        exTenderAnnQuaInqueryAnn.setUpdateBy(sysUser.getUsername());
        exTenderAnnQuaInqueryAnnService.updateById(exTenderAnnQuaInqueryAnn);
        return Result.OK("提交送审成功!");
    }

    @AutoLog(value = "审核")
    @ApiOperation(value = "审核", notes = "审核")
    @PostMapping(value = "/audit")
    public Result<String> audit(@RequestBody ExProjectParam exProjectParam) {
        exTenderAnnQuaInqueryAnnService.audit(exProjectParam);
        return Result.OK("审核成功!");
    }
}
